package org.rk.core.common.util.file;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.rk.core.common.util.RKAlert;
import org.rk.core.common.util.RKDateUtil;
import org.rk.core.common.util.RkStrUtil;
import org.rk.core.common.util.dateUtil.RKDateStyle;

public class DownloadUtils {

	public static void download(HttpServletRequest request, HttpServletResponse response, String filePath)
			throws IOException {
		download(request, response, filePath, "");
	}

	public static void download(HttpServletRequest request, HttpServletResponse response, String filePath,
			String displayName) {
		File file = new File(filePath);

		if (RkStrUtil.isEmpty(displayName)) {
			displayName = file.getName();
		}
		if (!file.exists() || !file.canRead()) {
			response.setContentType("text/html;charset=utf-8");
			try {
				response.getWriter().write("您下载的文件不存在！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				RKAlert.Error("读取文件发生错误！");
				e.printStackTrace();
			}
			return;
		}

		String userAgent = request.getHeader("User-Agent");
		boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);

		response.reset();
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "must-revalidate, no-transform");
		response.setDateHeader("Expires", 0L);

		response.setContentType("application/x-download");
		response.setContentLength((int) file.length());

		String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
		displayFilename = displayFilename.replace(" ", "_");
		if (isIE) {
			try {
				displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				RKAlert.Error("文件转码错误！");
				e.printStackTrace();
			}
			response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
		} else {
			try {
				displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				RKAlert.Error("文件转码错误！");
				e.printStackTrace();
			}
			response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);
		}
		BufferedInputStream is = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			is = new BufferedInputStream(new FileInputStream(file));
			IOUtils.copy(is, os);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
		}
	}

	public static void download(HttpServletRequest request, HttpServletResponse response, String displayName,
			byte[] bytes) throws IOException {
		if (ArrayUtils.isEmpty(bytes)) {
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			response.getWriter().write("您下载的文件不存在！");
			return;
		}

		String userAgent = request.getHeader("User-Agent");
		boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);

		response.reset();
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "must-revalidate, no-transform");
		response.setDateHeader("Expires", 0L);

		response.setContentType("application/x-download");
		response.setContentLength((int) bytes.length);

		String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
		displayFilename = displayFilename.replace(" ", "_");
		if (isIE) {
			displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
		} else {
			displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);
		}
		BufferedInputStream is = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			is = new BufferedInputStream(new ByteArrayInputStream(bytes));
			IOUtils.copy(is, os);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
		}
	}

	public static void download(HttpServletRequest request, HttpServletResponse response, String displayName,
			InputStream inputStream){
		if (inputStream == null) {
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			try {
				response.getWriter().write("您下载的文件不存在！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return;
		}
		if (!RkStrUtil.hasText(displayName)) {
			displayName = RKDateUtil.getNowStr(RKDateStyle.YYYYMMDDHHMMSS);
		}
		String userAgent = request.getHeader("User-Agent");
		boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);

		response.reset();
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "must-revalidate, no-transform");
		response.setDateHeader("Expires", 0L);

		response.setContentType("application/x-download");
		// response.setContentLength((int) bytes.length);
		BufferedInputStream is = null;
		OutputStream os = null;
		try{
			String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
			displayFilename = displayFilename.replace(" ", "_");
			if (isIE) {
				displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
				response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
			} else {
				displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
				response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);
			}
			os = response.getOutputStream();
			is = new BufferedInputStream(inputStream);
			IOUtils.copy(is, os);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
		}
	}

	public static void showImage(HttpServletRequest request, HttpServletResponse response, String filePath,
			String fileContent) {
		response.setDateHeader("Expires", 0L);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType(fileContent);

		File imgFile = new File(filePath);
		BufferedInputStream bis;
		ServletOutputStream out;
		try {
			bis = new BufferedInputStream(new FileInputStream(imgFile));
			out = response.getOutputStream();
			IOUtils.copy(bis, out);
			try {
				out.flush();
			} finally {
				out.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void showImage(HttpServletRequest request, HttpServletResponse response, String displayName,
			byte[] bytes) {
		response.setDateHeader("Expires", 0L);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentLength((int) bytes.length);

		BufferedInputStream is = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			is = new BufferedInputStream(new ByteArrayInputStream(bytes));
			IOUtils.copy(is, os);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
		}
	}

	public static void showImage(HttpServletRequest request, HttpServletResponse response, String displayName,
			InputStream inputStream) {
		response.setDateHeader("Expires", 0L);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		// response.setContentLength(inputStream.);
		if (!RkStrUtil.hasText(displayName)) {
			displayName = RKDateUtil.getNowStr(RKDateStyle.YYYYMMDDHHMMSS);
		}
		BufferedInputStream is = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			is = new BufferedInputStream(inputStream);
			IOUtils.copy(is, os);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
		}
	}

	public static void showPdfFile(HttpServletRequest request, HttpServletResponse response, String displayName,
			byte[] bytes) {
		response.setDateHeader("Expires", 0L);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("application/pdf");
		response.setContentLength((int) bytes.length);

		BufferedInputStream is = null;
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			is = new BufferedInputStream(new ByteArrayInputStream(bytes));
			IOUtils.copy(is, os);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
		}
	}
}
